<template>
  <div class="video-management">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索视频标题/描述"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="categoryFilter" placeholder="分类" clearable @change="handleSearch">
          <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态" clearable @change="handleSearch">
          <el-option label="待审核" value="pending" />
          <el-option label="处理中" value="processing" />
          <el-option label="已就绪" value="ready" />
          <el-option label="处理失败" value="failed" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
      </div>
      <div class="action-bar">
        <el-button type="primary" @click="showUploadDialog">
          <el-icon><Plus /></el-icon>上传视频
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedVideos.length">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>
    </div>

    <!-- 视频列表 -->
    <el-table
      v-loading="loading"
      :data="videos"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="视频信息" min-width="300">
        <template #default="{ row }">
          <div class="video-info">
            <div class="video-thumbnail" @click="handlePreview(row)">
              <el-image
                :src="getFullUrl(row.thumbnail)"
                :preview-src-list="[]"
                fit="cover"
                class="thumbnail-image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span class="duration">{{ formatDuration(row.duration) }}</span>
            </div>
            <div class="video-details">
              <div class="title">{{ row.title }}</div>
              <div class="uploader">
                上传者：{{ row.user?.username || '未知用户' }}
              </div>
              <div class="category-tag">
                <el-tag size="small">{{ row.category }}</el-tag>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="上传时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="观看/点赞" width="120">
        <template #default="{ row }">
          <div class="stats">
            <el-tooltip content="观看次数" placement="top">
              <span><el-icon><View /></el-icon> {{ row.views }}</span>
            </el-tooltip>
            <el-tooltip content="点赞数" placement="top">
              <span><el-icon><Star /></el-icon> {{ row.likes }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <template v-if="row.status === 'pending'">
              <el-button type="success" link @click="handleApproveVideo(row)">通过</el-button>
              <el-button type="warning" link @click="handleRejectVideo(row)">拒绝</el-button>
            </template>
            <el-button type="primary" link @click="handlePreview(row)">预览</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 视频预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="视频预览"
      width="800px"
      destroy-on-close
      class="video-preview-dialog"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div v-if="previewingVideo" class="video-preview">
        <video-player 
          :video-url="getFullUrl(previewingVideo?.formats?.[0]?.url)"
          :formats="previewingVideo?.formats?.map(f => ({ ...f, url: getFullUrl(f.url) }))"
          :preview-thumbnails="previewingVideo?.previewThumbnails"
          :preview-vtt="previewingVideo?.previewVtt"
          @error="handleVideoError"
        />
        <div class="video-info-preview">
          <h3>{{ previewingVideo.title }}</h3>
          <p class="description">{{ previewingVideo.description }}</p>
          <div class="tags">
            <el-tag
              v-for="tag in previewingVideo.tags"
              :key="tag"
              size="small"
              class="tag"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑视频对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑视频"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editingVideo"
        :rules="videoRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="editingVideo.title" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editingVideo.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editingVideo.category">
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="editingVideo.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editingVideo.status">
            <el-option label="处理中" value="processing" />
            <el-option label="已就绪" value="ready" />
            <el-option label="处理失败" value="failed" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveVideo" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 上传视频对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传视频"
      width="600px"
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="uploadForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入视频描述"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="uploadForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入或选择标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
              <el-form-item label="视频文件" prop="videoFile">
                <el-upload
                  ref="uploadRef"
                  v-model:file-list="uploadForm.videoFile"
                  action="#"
                  :limit="1"
                  :auto-upload="false"
                  :on-exceed="handleVideoFileExceed" 
                  :on-change="handleVideoFileChange" 
                >
                  <el-button type="primary">选择视频</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传一个视频文件，新文件会覆盖旧文件
                    </div>
                  </template>
                </el-upload>
              </el-form-item>

              <!-- 视频预览和截帧操作 -->
              <el-form-item label="视频预览与截帧" v-if="videoPreviewUrl">
                <div style="display: flex; flex-direction: column; gap: 10px;">
                  <video
                    ref="videoPlayerForFrameCapture"
                    :src="videoPreviewUrl"
                    controls
                    width="320"
                    height="180"
                    crossorigin="anonymous" 
                    @loadeddata="() => { /* 可以在这里处理视频加载完成事件 */ }"
                  ></video>
                  <el-button @click="captureFrame" type="success" :disabled="!videoPreviewUrl">
                    截取当前帧作为封面
                  </el-button>
                </div>
              </el-form-item>

              <!-- 截取的封面预览 -->
              <el-form-item label="封面预览" prop="capturedFrame" v-if="capturedFrameDataUrl">
                 <div style="display: flex; flex-direction: column; align-items: flex-start; gap: 10px;">
                  <img :src="capturedFrameDataUrl" alt="Captured Frame" style="max-width: 320px; max-height: 180px; border: 1px solid #ccc;" />
                  <el-button @click="clearCapturedFrame" type="danger" size="small">清除封面</el-button>
                </div>
              </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="uploadForm.userId" placeholder="请输入上传者的用户ID"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="uploadForm.status">
            <el-option label="待审核" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已就绪" value="ready" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUploadVideo" :loading="uploading">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Search, Delete, Picture, View, Star, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/services/axios.js' // 导入配置好的 axios 实例
import VideoPlayer from '@/components/VideoPlayer.vue' // 假设有视频播放器组件
import { formatDate, formatDuration } from '@/utils/formatters.js' // 假设有格式化工具函数

// 获取后端基础 URL
const backendUrl = import.meta.env.VITE_BACKEND_URL || window.location.origin; // 从环境变量读取，提供默认值

// 获取完整URL
const getFullUrl = (path) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  // 使用后端 URL 作为基础 URL 来拼接封面路径。
  // 确保 path 是以 / 开头，如果不是则添加
  const relativePath = path.startsWith('/') ? path : `/${path}`;
  return `${backendUrl}${relativePath}`
}

// 查询参数
const searchQuery = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')

// 表格数据
const videos = ref([])
const loading = ref(false)
const selectedVideos = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分类选项
const categories = [
  { label: '娱乐', value: '1' },
  { label: '音乐', value: '2' },
  { label: '游戏', value: '3' },
  { label: '科技', value: '4' },
  { label: '教育', value: '5' },
  { label: '生活', value: '6' },
  { label: '体育', value: '7' },
  { label: '新闻', value: '8' },
  { label: '电影', value: '9' }
 ];

// 常用标签
const commonTags = [
  '音乐', '游戏', '教育', '生活', '科技',
  '娱乐', '新闻', '体育', '动漫', 'vlog'
]

// 预览对话框
const previewDialogVisible = ref(false)
const previewingVideo = ref(null)

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const saving = ref(false)
const editingVideo = ref({
  title: '',
  description: '',
  category: '',
  tags: [],
  status: ''
})

// 表单验证规则
const videoRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 上传视频对话框
const uploadDialogVisible = ref(false)
const uploadFormRef = ref(null)
const uploading = ref(false) // Preserved from original structure
const uploadForm = ref({
  title: '',
  description: '',
  category: '',
  tags: [], // 初始化为空数组
  userId: '', // 管理员上传时需要指定用户ID
  status: 'pending', // 默认状态，与后端校验对应
  // 根据后端要求，预留字段，但具体值需要在上传前或上传过程中填充
  duration: 0, // 时长，单位秒，默认为0或从视频文件读取
  thumbnail: '', // 封面图URL，通常由后端生成或另外上传
  videoUrl: '', // 视频文件URL，通常由后端生成
  fileName: '', // 文件名，可以从上传的文件对象中获取
  videoFile: [], // 用于 el-upload 的文件列表
  // thumbnailFile: [] // 用于 el-upload 的封面文件列表 - 将被移除，改用截帧
})

// 用于视频截帧
const videoPlayerForFrameCapture = ref(null)
const videoPreviewUrl = ref('')
const capturedFrameDataUrl = ref('')
const capturedFrameFile = ref(null)

// Helper function to convert data URL to File object
async function dataURLtoFile(dataurl, filename) {
  if (!dataurl) return null;
  try {
    const arr = dataurl.split(',');
    if (arr.length < 2) throw new Error('Invalid data URL');
    const mimeMatch = arr[0].match(/:(.*?);/);
    if (!mimeMatch || mimeMatch.length < 2) throw new Error('Cannot find MIME type in data URL');
    const mime = mimeMatch[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  } catch (error) {
    console.error('Error converting data URL to File:', error);
    ElMessage.error('封面数据转换失败，请重试');
    return null;
  }
}

// 处理视频文件选择，用于截帧预览
const handleVideoFileChange = (file, fileList) => {
  if (file) {
    // 清除上一个视频的预览和截帧
    if (videoPreviewUrl.value) {
      URL.revokeObjectURL(videoPreviewUrl.value)
    }
    videoPreviewUrl.value = URL.createObjectURL(file.raw)
    uploadForm.value.videoFile = [file] // 保持单个文件
    // 清除已捕获的帧
    capturedFrameDataUrl.value = ''
    capturedFrameFile.value = null

    // 自动获取视频时长和文件名
    const videoElement = document.createElement('video');
    videoElement.preload = 'metadata';
    videoElement.onloadedmetadata = () => {
      uploadForm.value.duration = Math.round(videoElement.duration);
      URL.revokeObjectURL(videoElement.src); // 清理
    };
    videoElement.src = videoPreviewUrl.value;
    uploadForm.value.fileName = file.name;

  } else {
    // 清除视频预览和文件
    if (videoPreviewUrl.value) {
      URL.revokeObjectURL(videoPreviewUrl.value)
    }
    videoPreviewUrl.value = ''
    uploadForm.value.videoFile = []
    capturedFrameDataUrl.value = ''
    capturedFrameFile.value = null
    uploadForm.value.duration = 0;
    uploadForm.value.fileName = '';
  }
}

const handleVideoFileExceed = (files, fileList) => {
  ElMessage.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，已覆盖旧文件。`);
  // uploadRef.value.clearFiles(); // 清空已上传的文件列表
  // const file = files[0];
  // uploadRef.value.handleStart(file); // 手动选择第一个文件
  // 直接调用change处理，因为el-upload的auto-upload=false时，on-exceed后仍会触发on-change
};

// 截取当前视频帧作为封面
const captureFrame = async () => {
  if (!videoPlayerForFrameCapture.value || !videoPreviewUrl.value) {
    ElMessage.error('请先选择视频文件并等待加载')
    return
  }
  try {
    const videoElement = videoPlayerForFrameCapture.value
    const canvas = document.createElement('canvas')
    canvas.width = videoElement.videoWidth
    canvas.height = videoElement.videoHeight
    const ctx = canvas.getContext('2d')
    if (!ctx) {
        ElMessage.error('无法获取Canvas绘图上下文');
        return;
    }
    ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height)
    capturedFrameDataUrl.value = canvas.toDataURL('image/jpeg')
    capturedFrameFile.value = await dataURLtoFile(capturedFrameDataUrl.value, 'thumbnail.jpg')
    if (capturedFrameFile.value) {
        ElMessage.success('封面截取成功');
    } else {
        ElMessage.error('封面截取失败，文件转换出错');
    }
  } catch (error) {
    console.error('截取封面失败:', error)
    ElMessage.error('截取封面失败，请检查视频格式或浏览器兼容性')
  }
}

// 清除已截取的封面
const clearCapturedFrame = () => {
  capturedFrameDataUrl.value = ''
  capturedFrameFile.value = null
  ElMessage.info('已清除所选封面')
}

// 上传表单验证规则
const uploadRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  videoFile: [
    { required: true, message: '请选择视频文件', trigger: 'change' }
  ],
  // thumbnailFile: [
  //   { required: true, message: '请选择视频封面', trigger: 'change' }
  // ], // 移除，或改为自定义校验截帧是否存在
  capturedFrame: [
    { validator: (rule, value, callback) => {
        if (!capturedFrameFile.value) {
          callback(new Error('请从视频中截取封面'));
        } else {
          callback();
        }
      }, trigger: 'manual' // 或者在提交时手动触发
    }
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  // 根据后端要求，添加对新增字段的校验，如果它们是必填的
  // duration, thumbnail, videoUrl, fileName 的校验规则可以根据实际情况添加
  // 例如，如果 thumbnail 和 videoUrl 是 URL，可以添加 URL 格式校验
  // 这里暂时不添加，假设它们由其他逻辑填充或非严格必填于表单校验阶段
}

// 获取视频列表
const fetchVideos = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      search: searchQuery.value,
      category: categoryFilter.value,
      status: statusFilter.value
    }
    // 管理员获取视频列表，默认应包含所有状态，后端 getVideos 已处理
    const response = await http.get('/api/videos', { params }) // 使用 /api/videos，后端根据角色过滤
    videos.value = response.data.videos
    total.value = response.data.totalVideos
  } catch (error) {
    console.error('获取视频列表失败:', error)
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    processing: 'warning',
    ready: 'success',
    failed: 'danger',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待审核',
    processing: '处理中',
    ready: '已就绪',
    failed: '处理失败',
    rejected: '已拒绝'
  }
  return textMap[status] || '未知'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchVideos()
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedVideos.value = selection
}

// 预览视频
const handlePreview = (video) => {
  previewingVideo.value = video
  previewDialogVisible.value = true
}

// 编辑视频
const handleEdit = (video) => {
  editingVideo.value = { ...video }
  editDialogVisible.value = true
}

// 保存视频
const handleSaveVideo = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        await http.put(`/api/admin/videos/${editingVideo.value._id}`, editingVideo.value)
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        fetchVideos()
      } catch (error) {
        console.error('保存视频失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 审核通过视频
 const handleApproveVideo = async (video) => {
 try {
  await http.put(`/api/admin/videos/${video._id}/status`, { status: 'ready' })
   ElMessage.success('视频已通过审核')
   // 更新列表中的状态
   const index = videos.value.findIndex(v => v._id === video._id)
   if (index !== -1) {
     videos.value[index].status = 'ready'
   }
 } catch (error) {
   console.error('审核通过视频失败:', error)
   ElMessage.error('操作失败')
 }
}

// 拒绝视频
const handleRejectVideo = async (video) => {
 try {
   // 可以添加一个输入框让管理员填写拒绝原因
   const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因（可选）', '拒绝视频', {
     confirmButtonText: '确定拒绝',
     cancelButtonText: '取消',
     inputPattern: /.*/, // 允许为空
     inputErrorMessage: '',
   })

   await http.put(`/api/admin/videos/${video._id}/status`, { status: 'rejected', reason })
   ElMessage.success('视频已拒绝')
   // 更新列表中的状态
   const index = videos.value.findIndex(v => v._id === video._id)
   if (index !== -1) {
     videos.value[index].status = 'rejected'
     // 可以考虑同时更新 errorMessage 字段
     // videos.value[index].errorMessage = reason;
   }
 } catch (error) {
   if (error !== 'cancel') {
     console.error('拒绝视频失败:', error)
     ElMessage.error('操作失败')
   }
 }
}

// 删除视频
const handleDelete = async (video) => {
  try {
    await ElMessageBox.confirm(`确定要删除视频 "${video.title}" 吗？`, '警告', { // 修正模板字符串
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await http.delete(`/api/admin/videos/${video._id}`)
    ElMessage.success('删除成功')
    // 从列表中移除
    const index = videos.value.findIndex(v => v._id === video._id)
    if (index !== -1) {
      videos.value.splice(index, 1)
      total.value -= 1
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除视频失败:', error)
      ElMessage.error('删除视频失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedVideos.value.length} 个视频吗？此操作不可恢复`)
    const videoIds = selectedVideos.value.map(video => video._id)
    await http.post('/api/admin/videos/batch-delete', { videoIds })
    ElMessage.success('批量删除成功')
    fetchVideos()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchVideos()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchVideos()
}

// 处理视频错误
const handleVideoError = (error) => {
  ElMessage.error(error)
}

// 显示上传对话框
const showUploadDialog = () => {
  uploadForm.value = {
    title: '',
    description: '',
    category: '',
    tags: [],
    userId: '',
    status: 'draft'
  }
  uploadDialogVisible.value = true
}

// 上传视频
const handleUploadVideo = async () => {
  if (!uploadFormRef.value) return

  // Manually validate the capturedFrame before proceeding
  let capturedFrameValid = true;
  if (uploadFormRef.value) {
      try {
          await uploadFormRef.value.validateField('capturedFrame');
      } catch (error) {
          // If validation fails for capturedFrame, error will be an array of validation errors
          // We just need to know it failed, specific error messages are handled by the form item itself.
          capturedFrameValid = false;
      }
  }

  await uploadFormRef.value.validate(async (valid) => {
    if (valid && capturedFrameValid) { // Ensure both form and captured frame are valid
      uploading.value = true
      try {
        const formData = new FormData()
        formData.append('title', uploadForm.value.title)
        formData.append('description', uploadForm.value.description)
        formData.append('category', uploadForm.value.category)
        formData.append('tags', JSON.stringify(uploadForm.value.tags))
        formData.append('userId', uploadForm.value.userId)
        formData.append('status', uploadForm.value.status)

        if (uploadForm.value.videoFile && uploadForm.value.videoFile.length > 0) {
          const videoFileRaw = uploadForm.value.videoFile[0].raw;
          formData.append('video', videoFileRaw);
          formData.append('fileName', uploadForm.value.fileName || videoFileRaw.name);
        } else {
          ElMessage.error('请选择视频文件');
          uploading.value = false;
          return;
        }

        // 使用截取的帧作为封面
        if (capturedFrameFile.value) {
          formData.append('thumbnail_image', capturedFrameFile.value);
        } else {
          ElMessage.error('请从视频中截取封面图片');
          uploading.value = false;
          return;
        }

        formData.append('duration', uploadForm.value.duration.toString());
        // videoUrl and thumbnail (string) are usually generated by backend after upload
        // So we might not need to send them from client, or send placeholder/empty if required by API
        formData.append('videoUrl', uploadForm.value.videoUrl || ''); // Or handle as per API spec

        await http.post('/api/admin/videos', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        ElMessage.success('视频创建成功')
        uploadDialogVisible.value = false
        // Reset form and captured frame state after successful upload
        if (uploadFormRef.value) uploadFormRef.value.resetFields();
        videoPreviewUrl.value = '';
        capturedFrameDataUrl.value = '';
        capturedFrameFile.value = null;
        uploadForm.value.videoFile = [];
        fetchVideos() // 刷新视频列表
      } catch (error) {
        console.error('创建视频失败:', error)
        ElMessage.error(error.response?.data?.message || '创建视频失败')
      } finally {
        uploading.value = false
      }
    } else {
        if (!capturedFrameValid) {
            // This message is a fallback, usually the form item itself shows the error.
            ElMessage.error('请确保已截取封面');
        }
    }
  })
}

// 初始化
onMounted(() => {
  fetchVideos()
})
</script>

<style scoped>
.video-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
}

.search-bar .el-input {
  width: 200px;
}

.video-info {
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 16px; /* 设置元素之间的间距 */
}

.video-thumbnail {
  position: relative;
  width: 160px;
  height: 90px;
  cursor: pointer;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.image-placeholder .el-icon {
  font-size: 24px;
  color: #909399;
}

.duration {
  position: absolute;
  bottom: 4px;
  right: 4px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
}

.video-details {
  flex: 1;
  display: flex;
  flex-direction: column; /* 内部元素垂直排列 */
  gap: 4px; /* 详情内部元素间距 */
  flex-grow: 1; /* 占据剩余空间 */
}

.title {
  font-weight: bold;
  margin-bottom: 4px;
}

.uploader {
  font-size: 13px;
  color: #606266;
}

.stats {
  display: flex;
  gap: 10px;
  color: #606266;
}

.stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.video-preview {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-info-preview {
  padding: 0 20px;
}

.video-info-preview h3 {
  margin: 0 0 10px 0;
}

.description {
  color: #606266;
  margin-bottom: 10px;
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  margin-right: 0;
}

:deep(.video-preview-dialog .el-dialog) {
  background-color: #fff !important;
  z-index: 2000 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.video-preview-dialog .el-dialog__body) {
  background-color: #fff; /* 移除 !important */
  padding: 0;
}

:deep(.video-preview-dialog .el-dialog__header) {
  background-color: #fff !important;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

:deep(.video-preview-dialog .el-dialog__wrapper) {
  overflow: hidden;
}

:deep(.video-preview-dialog .el-overlay) {
  background-color: rgba(0, 0, 0, 1) !important; 
  z-index: 1999 !important; 
}

.video-preview {
  display: flex;
  flex-direction: column;
  gap: 20px;
 background-color: #fff;
}
</style>